from aiogram import Bot, Dispatcher
from aiogram.filters import Text
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import any_state
from aiogram.types import Message
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.filters.admin import AdminFilter
from app.bot.keyboards.reply import admin_keyboard, yes_no_button
from app.bot.states.states import Broadcast
from app.bot.utils.broadcaster import broadcast
from app.config import Settings
from app.database.functions.user import get_users


async def send_messages(message: Message, state: FSMContext) -> None:
    await message.answer("Введите текст для рассылки")
    await state.set_state(Broadcast.waiting_message)


async def select_message_text(message: Message, state: FSMContext) -> None:
    await state.update_data(post=message.text)
    await message.answer(message.text)
    await message.answer("Подтверждаете рассылку?", reply_markup=yes_no_button())
    await state.set_state(Broadcast.waiting_confirmation)


async def confirm(
    message: Message,
    bot: Bot,
    config: Settings,
    session: AsyncSession,
    state: FSMContext,
) -> None:
    if message.text == "Да":
        data = await state.get_data()
        await message.answer("Рассылка запущена", reply_markup=admin_keyboard())
        users = await get_users(session)
        messages_sent, errors_count = await broadcast(bot, users, data.get("post"))
        await broadcast(
            bot,
            config.tg_bot.admin_ids,
            (
                f"Рассылка закончена\n"
                f"Успешно отправлено сообщений: {messages_sent}\n"
                f"С ошибкой: {errors_count}\n"
                f"Всего пользователей: {len(users)}"
            ),
        )
    elif message.text == "Нет":
        await message.answer(
            "Рассылка не была отправлена", reply_markup=admin_keyboard()
        )
    await state.clear()


def register_admin_handlers(dp: Dispatcher):
    dp.message.register(
        send_messages,
        Text(text="💬 Сделать рассылку", ignore_case=True),
        AdminFilter(),
        any_state,
    )
    dp.message.register(select_message_text, Broadcast.waiting_message)
    dp.message.register(confirm, Broadcast.waiting_confirmation)
